package com.wolfking.converter.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Sets;
import com.wolfking.converter.config.ClassnameConfig;
import com.wolfking.converter.entity.SqlDefine;
import com.wolfking.converter.entity.SqlFieldTransform;
import com.wolfking.converter.event.SqlFieldTransformEvent;
import com.wolfking.converter.service.SqlDefineService;
import com.wolfking.converter.service.SqlFieldTransformService;
import com.wolfking.jeesite.config.SsoConfig;
import com.wolfking.jeesite.entity.PageInfo;
import com.wolfking.jeesite.sign.Sign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/sql/fieldTransform")
public class SqlFiledTransformController {

    @Autowired
    private SqlDefineService defineService;

    @Autowired
    private SqlFieldTransformService sqlFieldTransformService;

    @Autowired
    private SsoConfig ssoConfig;

    @Autowired
    private ClassnameConfig classnameConfig;

    @Sign(code = "sql:fieldTransform:view")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public String list(Model model, SqlFieldTransform sqlFieldTransform,
                       @RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "30") int pageSize) {
        List<SqlDefine> defineList = defineService.list();
        QueryWrapper<SqlFieldTransform> queryWrapper = sqlFieldTransformService.queryWrapperConfig(sqlFieldTransform,
                Sets.newHashSet("defineKey", "fieldName"), Sets.newHashSet());
        queryWrapper.orderByDesc("id");
        PageInfo<SqlFieldTransform> page =
                sqlFieldTransformService.pageQuery(queryWrapper, pageNum, pageSize);
        model.addAttribute("defineList", defineList);
        model.addAttribute("page", page);
        model.addAttribute("fieldTransform", sqlFieldTransform);
        model.addAttribute("defineMap", defineList.stream().collect(
                Collectors.toMap(SqlDefine::getDefineKey, SqlDefine::getSqlDescribe)));
        return "sql/fieldTransform/list";
    }


    @Sign(code = "sql:fieldTransform:view")
    @RequestMapping(value = "/edit", method = {RequestMethod.GET})
    public String editGet(Model model, @RequestParam(name = "id", required = false) Integer id,
                          @RequestParam(name = "defineKey", required = false) String defineKey) {
        List<SqlDefine> defineList = defineService.list();
        model.addAttribute("defineList", defineList);
        if (Objects.nonNull(id)) {
            SqlFieldTransform byId = sqlFieldTransformService.getById(id);
            if (Objects.isNull(byId)) {
                byId = new SqlFieldTransform();
            }
            model.addAttribute("fieldTransform", byId);
        } else {
            final SqlFieldTransform sqlFieldTransform = new SqlFieldTransform();
            if (StringUtils.isNotBlank(defineKey)) {
                sqlFieldTransform.setDefineKey(defineKey);
            }
            model.addAttribute("fieldTransform", sqlFieldTransform);
        }
        model.addAttribute("classnames", classnameConfig.getTransformClassSet());
        return "sql/fieldTransform/edit";
    }


    @Sign(code = "sql:fieldTransform:edit",event = SqlFieldTransformEvent.class)
    @RequestMapping(value = "/edit", method = {RequestMethod.POST})
    public String editPost(RedirectAttributes redirectAttributes, SqlFieldTransform data) throws Exception {
        if (StringUtils.isNotBlank(data.getConstructArg())) {
            data.setConstructArg(data.getConstructArg().trim());
        }
        if (StringUtils.isNotBlank(data.getTransform())) {
            data.setTransform(data.getTransform().trim());
        }
        if (Objects.isNull(data.getId())) {
            sqlFieldTransformService.save(data);
            redirectAttributes.addFlashAttribute("message", "添加转换器成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "修改转换器成功");
            sqlFieldTransformService.updateById(data);
            data = sqlFieldTransformService.getById(data.getId());
        }
        return ssoConfig.getRedirectWithPath(String.format("/sql/fieldTransform/list?defineKey=%s&fieldName=%s",
                data.getDefineKey(), URLEncoder.encode(data.getFieldName(), "UTF-8")));
    }

    @Sign(code = "sql:fieldTransform:edit")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET})
    public String delete(RedirectAttributes redirectAttributes, @RequestParam("id") Integer id) {
        SqlFieldTransform sqlFieldTransform = sqlFieldTransformService.getById(id);
        sqlFieldTransformService.deleteById(id);
        redirectAttributes.addFlashAttribute("message", "删除转换器成功");
        if (Objects.isNull(sqlFieldTransform)) {
            return ssoConfig.getRedirectWithPath("/sql/fieldTransform/list");
        } else {
            return ssoConfig.getRedirectWithPath("/sql/fieldTransform/list?defineKey=" + sqlFieldTransform.getDefineKey());
        }
    }
}
